﻿using System;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 用户签入签出
    /// </summary>
    public class SignController : BaseApiController
    {
        //private static ILogger<SettlementManageController> _Logger;
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ISignService _SignService;
        private readonly ILoginLogic _loginLogic;

        /// <inheritdoc />
        public SignController(ISignService signService,
            //ILogger<SettlementManageController> logger,
            ILoginLogic loginLogic
            )
        {
            _SignService = signService;
            //_Logger = logger;
            _loginLogic = loginLogic;
        }

        /// <summary>
        /// 验证码获取
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task VerifyCode()
        {
            Response.ContentType = "image/jpeg";
            using (var stream = VerifyCodeHelper.Create(out string code))
            {
                var buffer = stream.ToArray();
                var opetion = new CookieOptions {Domain = ".aixiyou.com:3385" };
                // 将验证码的token放入cookie
                Response.Cookies.Append("VerifyCode", _SignService.GetVerifyCodeToken(code));
                await Response.Body.WriteAsync(buffer, 0, buffer.Length);
            }
            
        }
        /// <summary>
        /// 签入
        /// </summary>
        /// 
        [Microsoft.AspNetCore.Cors.EnableCors("any")]//跨域
        [HttpPost]
        public IActionResult SignInVc([FromBody]dynamic obj)
        {
            try
            {
                var username = Convert.ToString(obj.username);
                var password = Convert.ToString(obj.password);
                var varifyCode = obj.varifyCode.ToString();
                var vcToken = obj.vcToken.ToString();
                //验证码
                var isvc = _SignService.CheckVerifyCodeToken(varifyCode, vcToken);
                if (!isvc)
                    return Ok(new { errcode = 1, msg = "验证码错误" });
                //原始代码 
                //用户密码
                //var loginMatching = _loginLogic.LoginMatching(username, password, out string staffId, out string roleId, out string areaId);
                //if(!loginMatching)
                //    return Ok(new { errcode = 1, msg = "用户名密码错误" });
                ////生成token，整体结果
                //var isSuccess = _SignService.TrySign(username, staffId, roleId,areaId, out string token);

                User user = _loginLogic.LoginMatching(username, password);
                if (user == null)
                    return Ok(new { errcode = 1, msg = "用户名密码错误" });
                //生成token，整体结果
                var isSuccess = _SignService.TrySign(user.Name, user.Id.ToString(), user.RoleId, user.SiteId, out string token);
                return isSuccess
                    ? Ok(new { errcode = 0, msg = "登录成功", data = new { token } })
                    : Ok(new { errcode = 1, msg = "登录失败" });
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return Ok(new { errcode = 1, msg = "登录失败" });
            }
        }
        /// <summary>
        /// 签入
        /// </summary>
        [HttpPost]
        public IActionResult SignIn([FromBody]dynamic obj)
        {
            try
            {
                var username = Convert.ToString(obj.username);
                var password = Convert.ToString(obj.password);
                //用户密码
                var loginMatching = _loginLogic.LoginMatching(username, password, out string staffId, out string roleId, out string areaId);
                if (!loginMatching)
                    return Ok(new { errcode = 1, msg = "用户名密码错误" });
                //生成token，整体结果
                var isSuccess = _SignService.TrySign(username, staffId, roleId,areaId, out string token);
                return isSuccess
                    ? Ok(new { errcode = 0, msg = "登录成功", data = new { token } })
                    : Ok(new { errcode = 1, msg = "登录失败" });
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return Ok(new { errcode = 1, msg = "登录失败" });
            }
        }
    }
}